const { ccclass, property, executeInEditMode, menu, playOnFocus } = cc._decorator;

@ccclass
@executeInEditMode
@playOnFocus
@menu('cccframework/' + LoopBg.name)
export default class LoopBg extends cc.Component {

    @property({
        type: cc.Float,
        slide: true,
        range: [0, 500],
    })
    moveSpeed: number = 0;

    @property({ type: cc.Integer })
    get totalWidth(): number {
        let totalWidth = 0;
        for (let i of this.bgs) {
            totalWidth += i.width;
        }
        return totalWidth;
    }
    @property({ type: cc.Integer })
    get totalHeight(): number {
        let totalHeight = 0;
        for (let i of this.bgs) {
            totalHeight += i.height;
        }
        return totalHeight;
    }

    @property({ type: [cc.Node] })
    get bgs(): cc.Node[] {
        return this.node.children.filter((v) => {
            return v && v.isValid && v.active;
        })
    }
    onLoad() {
        if (this.bgs.length > 1) {
            this.updateAllBgSize();
            this.resetAllBgPos();
        } else {
            console.error('子节点数量至少要两个才能开始循环')
        }
        this.node.on(cc.Node.EventType.CHILD_ADDED, this.updateAllBgSize, this)
        this.node.on(cc.Node.EventType.CHILD_REMOVED, this.updateAllBgSize, this)
    }
    resetAllBgPos() {
        // 更新位置
        let bgs = this.bgs;
        let totalWidth = this.totalWidth;
        let bgWidth = cc.winSize.width;

        for (let i = 0; i < bgs.length; i++) {
            let bg = bgs[i];
            bg.position = cc.v2(-totalWidth / 2 + i * bgWidth, 0)
        }
        // 更新宽度

    }
    updateAllBgSize() {
        let bgs = this.bgs;
        for (let i = 0; i < bgs.length; i++) {
            let bg = bgs[i];
            bg.setContentSize(cc.winSize);
            CC_EDITOR && Editor.log(cc.winSize.width.toString(), cc.winSize.height.toString())
        }
        // 更新宽度
        this.node.width
    }

    moveAllBg() {
        let bgs = this.bgs;
        let totalWidth = this.totalWidth;
        if (bgs.length > 1) {
            bgs.forEach(v => {
                v.x += this.moveSpeed * this.dt;
                if (v.x > totalWidth/2) {
                    v.x -= totalWidth ;
                } else if (v.x < -totalWidth/2) {
                    v.x += totalWidth ;
                }
            })
        }
    }
    dt: number = 0;
    update(dt) {
        this.dt = dt;
        this.moveAllBg();
    }
}
